import {defaultRoutes,asyncRoutes, constantRoutes } from '@/router'
import common from '@/utils/common'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
/**function hasPermission(roles, route) {
  console.log('sfdsfdsf>'+roles)
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}*/
/**
 * 权限过滤
 * @param {} roles
 * @param {*} route
 */
function hasPermission(roles, route) {
  return true;
  if(route.meta ){
    let subsysid=common.subsysinfo.curid;
    if(route.meta.subsysid!=subsysid) return false;
    let menuid=route.meta.menuid||route.meta.title;
    return roles.some(role=>role==menuid);
  }
  return true;
}
function getRoutesMap(routes){
  let res = {};
  routes.forEach(route => {
    const tmp = { ...route }
    if(route.url){
      res[route.url]=tmp;
    }
    if (tmp.children) {
      res=Object.assign(res,getRoutesMap(tmp.children));
    }

  });
  return res;
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles,menuids) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }

    if (hasPermission(menuids, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles,menuids)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  routesMap:{},
  isLoaded:false,
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
   // let m=getRoutesMap(state.routes);
   // Object.assign(state.routesMap,m);
  },
  SET_LOADED(state){
    state.isLoaded=true;
  },
  SAVE_ROUTES_CFG(state,config){
    // console.log(config);
    state.routesMap[config["url"]]=config;
  }
}

const actions = {
  openWin({},winPath){
    for(let i=0;i<routes.length;i++){

    }
  },
  saveRouteCfg({commit},config){
    commit("SAVE_ROUTES_CFG",config)
  },
  setRouters({commit},ruters){
    let tem=[];
    commit("SET_ROUTES",ruters)
  },
  setLoaded({commit}){
    commit("SET_LOADED");
  },
  generateRoutes1({ commit }, obj){
    return new Promise(resolve => {
      let s=defaultRoutes||[];
      s[s.length-1].children.concat(...obj)
      commit('SET_ROUTES',obj);
      resolve(s)
    });
  },
  generateRoutes({ commit }, obj) {
    let roles=obj.roles,menuids=obj.menuids;
    return new Promise(resolve => {
      let accessedRoutes=constantRoutes || []
      // if (roles.includes('admin')) {
         accessedRoutes = defaultRoutes || []
      // } else {
       //  accessedRoutes = filterAsyncRoutes(asyncRoutes, roles,menuids)
      // }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
